//
//  TalkManage.m
//  QuanZiChat
//
//  Created by lanou3g on 15/11/25.
//  Copyright © 2015年 ZhongHongLin. All rights reserved.
//

#import "TalkManage.h"
#import "Person.h"
#import "TalkRecord.h"
#import "ContactManManager.h"
#import "MessageInfo.h"
#import "MessageFrame.h"

@interface TalkManage()
@property(nonatomic,strong)Person *person;

@end

@implementation TalkManage

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;


static TalkManage *Manage = nil;
+(instancetype)defulManage{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Manage = [[TalkManage alloc] init];
    });
    return Manage;
}

////将聊天记录保存到本地
//-(void)addContentWithEntityForType:(NSNumber *)type Time:(NSString *)time Message:(NSString *)message UserID:(NSString *)userID Username:(NSString *)username{
//    //打开TalkRecord表
//    TalkRecord *content = [NSEntityDescription insertNewObjectForEntityForName:@"TalkRecord" inManagedObjectContext:self.managedObjectContext];
//    //给TalkRecord表里属性赋值
//    content.type = type;
//    content.content = message;
//    NSDate *date = [NSDate date];
//    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
//    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
//    NSString *timeString = [formatter stringFromDate:date];
//    content.time = timeString;
//    //打开Person表
//    static Person *person;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
//        //给Person表里的属性赋值
//        person.userID = userID;
//        person.username = username;
//        person.myname = @"haha";
//
//    });
//    [person addContentsObject:content];
//    //调用保存数据方法
//    [self saveContext];
//}

//从本地获取存储的好友信息
-(NSArray *)getbackFriendMessageFromCocaDataWithUsername:(NSString *)username{
    //实例化查询条件
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    //实体描述
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:self.managedObjectContext];
    [fetch setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"username = %@",username];
    [fetch setPredicate:predicate];
    NSError *error = nil;
    //使用管理对象上下文执行搜索请求
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetch error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"%@",error);
    }
    return fetchedObjects;
}




//从本地数据库获取会话内容按时间排序
-(void)getMessageSortWithClick:(NSString *)click{
    //清空数组
    [[[ContactManManager defaulManager] getTalkArray] removeAllObjects];
    //获取到本地存储的聊天记录
    Person *person = [self fetchWithUserID:click EntityForName:@"Person"].lastObject;
    //将聊天记录转化为messageframe类型的存入数组中
    for (TalkRecord *talk in person.contents) {
        MessageInfo *messageinfo = [[MessageInfo alloc] init];
        MessageFrame *messageFrame = [[MessageFrame alloc] init];
        messageinfo.time = talk.time;
        messageinfo.type = talk.type.intValue;
        messageinfo.text = talk.content;
        messageFrame.messageinfo = messageinfo;
        [[[ContactManManager defaulManager] getTalkArray] addObject:messageFrame];
    }
    //将聊天记录按时间顺序排序
    [[[ContactManManager defaulManager] getTalkArray] sortUsingComparator:^NSComparisonResult(MessageFrame *obj1, MessageFrame *obj2) {
        MessageInfo *message1 = obj1.messageinfo;
        MessageInfo *message2 = obj2.messageinfo;
        return [message1.time compare:message2.time];
    }];
}



//从本地查询聊天记录
-(NSArray *)fetchWithUserID:(NSString *)userID EntityForName:(NSString *)entityname{
    //实例化查询请求对象
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    //实体描述
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityname inManagedObjectContext:self.managedObjectContext];
    [fetch setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userID = %@",userID];
    [fetch setPredicate:predicate];
    NSError *error = nil;
    //使用管理对象上下文执行搜索请求
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetch error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"%@",error);
    }
    return fetchedObjects;
}

//从本地查询所有聊天的人
-(NSArray *)fetchTalkWithMyID:(NSString *)myID{
    //实例化查询请求对象
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    //实体描述
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
    [fetch setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myname = %@",myID];
    [fetch setPredicate:predicate];
    NSError *error = nil;
    //使用管理对象上下文执行搜索请求
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetch error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"%@",error);
    }
    return fetchedObjects;
}


/**
 时间戳转换为正常的时间
 */
- (NSString *)getNowTime:(NSInteger )time {
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    return [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:time / 1000]];;
}



- (NSURL *)applicationDocumentsDirectory {
    //输出一下路径
    NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

//被管理的对象模型
- (NSManagedObjectModel *)managedObjectModel {
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    //找到当前项目中的可视化的表文件(表名)
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"TaikPerson" withExtension:@"momd"];
    //根据路径将文件转换为一个对象
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}


//持久化存储助理:相当于数据库的连接器
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    //实例化一个链接器并且链接一个模型对象
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    //找到documents路径 并在该路径后面拼接CoreData.sqlist作为数据可的实体文件存在
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"LeancloudChat.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    //连接器使用哪种类型作为数据库文件的存储方式,并且在版本迁移/更新时要用更改potions参数
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:@{NSInferMappingModelAutomaticallyOption:@YES,NSMigratePersistentStoresAutomaticallyOption:@YES} error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}

//被管理的上下文:操作实际内容
- (NSManagedObjectContext *)managedObjectContext {
    
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    //找到连接器
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    //实例化管理对象上下文(管理器)并使用主线程的方式
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

//保存上下文
- (void)saveContext {
    //找到管理者(管理对象上下文)模型
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    //判断管理者是否为空
    if (managedObjectContext != nil) {
        NSError *error = nil;
        //判断管理者'是否发生了变化
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}
@end
